// 房间管理相关功能
const RoomManager = {
    // 加载房间列表
    async loadRooms() {
        const buildingId = document.getElementById('buildingSelect').value;
        if (!buildingId) {
            document.getElementById('roomList').innerHTML = `
                <div class="empty-state">
                    <p>请先选择宿舍楼</p>
                </div>
            `;
            return;
        }

        loading.show();
        try {
            const rooms = await API.rooms.getByBuilding(buildingId);
            const roomList = document.getElementById('roomList');
            
            if (!rooms || rooms.length === 0) {
                roomList.innerHTML = `
                    <div class="empty-state">
                        <p>该宿舍楼暂无房间</p>
                        <button class="btn btn-primary" onclick="RoomManager.showAddForm()">
                            <i class="icon add-icon"></i>添加房间
                        </button>
                    </div>
                `;
                return;
            }

            roomList.innerHTML = rooms.map(room => `
                <div class="room-card">
                    <div class="room-header">
                        <h3>${room.roomNumber}</h3>
                        <div class="room-stats">
                            <span class="occupancy-rate">
                                入住率: ${((room.currentOccupancy / room.capacity) * 100).toFixed(1)}%
                            </span>
                            <span class="capacity">
                                ${room.currentOccupancy}/${room.capacity}
                            </span>
                        </div>
                    </div>
                    <div class="room-content">
                        <div class="student-list">
                            ${room.students.map(student => `
                                <div class="student-item">
                                    <span>${student.name}</span>
                                    <span class="student-number">${student.studentNumber}</span>
                                </div>
                            `).join('') || '<p class="empty-text">暂无学生</p>'}
                        </div>
                    </div>
                    <div class="room-footer">
                        <button class="btn btn-secondary" onclick="RoomManager.showDetails(${room.id})">
                            <i class="icon student-icon"></i>查看学生
                        </button>
                        <button class="btn btn-primary" onclick="HygieneManager.showRecords(${room.id})">
                            <i class="icon hygiene-icon"></i>卫生记录
                        </button>
                        <button class="btn btn-danger" onclick="RoomManager.delete(${room.id})">
                            <i class="icon delete-icon"></i>删除
                        </button>
                    </div>
                </div>
            `).join('');
        } catch (error) {
            Debug.error('加载房间列表失败:', error);
            document.getElementById('roomList').innerHTML = `
                <div class="error-state">
                    <p>加载失败: ${error.message}</p>
                    <button class="btn btn-primary" onclick="RoomManager.loadRooms()">重试</button>
                </div>
            `;
        } finally {
            loading.hide();
        }
    },

    // 加载宿舍楼选择框
    async loadBuildingSelect() {
        Debug.log('Loading building select...');
        loading.show();
        try {
            const buildings = await API.buildings.getAll();
            Debug.log('Loaded buildings:', buildings);
            
            const buildingSelect = document.getElementById('buildingSelect');
            if (!buildingSelect) {
                Debug.error('Building select element not found');
                return;
            }
            
            if (!buildings || buildings.length === 0) {
                buildingSelect.innerHTML = '<option value="">暂无宿舍楼</option>';
                document.getElementById('roomList').innerHTML = `
                    <div class="empty-state">
                        <p>请先添加宿舍楼</p>
                        <button class="btn btn-primary" onclick="showSection('buildings')">
                            <i class="icon building-icon"></i>去添加宿舍楼
                        </button>
                    </div>
                `;
                return;
            }

            // 保留选择宿舍楼选��，并添加所有宿舍楼信息
            buildingSelect.innerHTML = `
                <option value="">选择宿舍楼</option>
                ${buildings.map(building => `
                    <option value="${building.id}">${building.buildingName}</option>
                `).join('')}
            `;

            // 显示所有宿舍楼的概览信息
            document.getElementById('roomList').innerHTML = `
                <div class="building-overview">
                    <div class="building-overview-content">
                        <div class="overview-header">
                            <h3>宿舍楼概览</h3>
                            <p class="overview-subtitle">选择一个宿舍楼查看详细房间信息</p>
                        </div>
                        <div class="building-cards">
                            ${buildings.map(building => `
                                <div class="building-card" onclick="RoomManager.selectBuilding(${building.id})">
                                    <div class="building-card-header">
                                        <h4>${building.buildingName}</h4>
                                        <span class="building-floors">${building.floors}层</span>
                                    </div>
                                    <div class="building-card-content">
                                        <div class="building-stats">
                                            <div class="stat-item">
                                                <span class="stat-label">总房间数</span>
                                                <span class="stat-value">${building.totalRooms || 0}</span>
                                            </div>
                                            <div class="stat-item">
                                                <span class="stat-label">入住率</span>
                                                <span class="stat-value">${building.occupancyRate ? building.occupancyRate.toFixed(1) : '0'}%</span>
                                            </div>
                                        </div>
                                        <div class="building-description">
                                            ${building.description || '暂无描述'}
                                        </div>
                                    </div>
                                    <div class="building-card-footer">
                                        <span class="view-rooms">查看房间 <i class="icon room-icon"></i></span>
                                    </div>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </div>
            `;

            Debug.log('Building select updated');
        } catch (error) {
            Debug.error('加载宿舍楼列表失败:', error);
            const buildingSelect = document.getElementById('buildingSelect');
            if (buildingSelect) {
                buildingSelect.innerHTML = '<option value="">加载失败</option>';
            }
            document.getElementById('roomList').innerHTML = `
                <div class="error-state">
                    <p>加载宿舍楼列表失败: ${error.message}</p>
                    <button onclick="RoomManager.loadBuildingSelect()">重试</button>
                </div>
            `;
        } finally {
            loading.hide();
        }
    },

    // 显示添加房间表单
    showAddForm() {
        const buildingId = document.getElementById('buildingSelect').value;
        if (!buildingId) {
            alert('请先选择宿舍楼');
            return;
        }
        document.getElementById('roomFormBuildingId').value = buildingId;
        showModal('addRoomModal');
    },

    // 显示房间详情（学生列表）
    async showDetails(roomId) {
        const modal = document.createElement('div');
        modal.className = 'modal active';
        modal.innerHTML = `
            <div class="modal-content">
                <button type="button" class="modal-close" onclick="this.closest('.modal').remove()"></button>
                <h3>房间学生列表</h3>
                <div id="roomStudentList"></div>
            </div>
        `;
        document.body.appendChild(modal);

        try {
            const students = await API.students.getByRoom(roomId);
            const studentList = document.getElementById('roomStudentList');
            
            if (!students || students.length === 0) {
                studentList.innerHTML = `
                    <div class="empty-state">
                        <p>暂无学生入住</p>
                    </div>
                `;
                return;
            }

            studentList.innerHTML = students.map(student => `
                <div class="list-item">
                    <div class="student-info">
                        <h4>${student.name}</h4>
                        <p>学号：${student.studentNumber}</p>
                        <p>性别：${student.gender}</p>
                        <p>电话：${student.phone || '无'}</p>
                    </div>
                </div>
            `).join('');
        } catch (error) {
            Debug.error('加载学生列表失败', error);
            document.getElementById('roomStudentList').innerHTML = `
                <div class="error-state">
                    <p>加载失败: ${error.message}</p>
                </div>
            `;
        }
    },

    // 删除房间
    async delete(id) {
        if (!confirm('确定要删除这个房间吗？删除后将无法恢复。')) {
            return;
        }

        try {
            loading.show();
            Debug.log('开始删除房间:', id);
            await API.rooms.delete(id);
            Debug.log('房间删除成功:', id);
            
            // 重新加载房间列表
            const buildingId = document.getElementById('buildingSelect').value;
            if (buildingId) {
                Debug.log('重新加载房间列表');
                await this.loadRooms();
            } else {
                Debug.log('重新加载宿舍楼列表');
                await this.loadBuildingSelect();
            }
        } catch (error) {
            Debug.error('删除房间失败:', error);
            alert('删除房间失败: ' + (error.message || '未知错误'));
        } finally {
            loading.hide();
        }
    },

    // 选择宿舍楼
    selectBuilding(buildingId) {
        try {
            // 更��选择框的值
            const buildingSelect = document.getElementById('buildingSelect');
            buildingSelect.value = buildingId;
            
            // 加载该宿舍楼的房间列表
            this.loadRooms();
            
            // 滚动到顶部
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
        } catch (error) {
            Debug.error('选择宿舍楼失败:', error);
            alert('选择宿舍楼失败: ' + error.message);
        }
    },

    // 初始化事件监听
    init() {
        // 添加房间表单提交处理
        document.getElementById('addRoomForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData(e.target);
            const room = {
                roomNumber: formData.get('roomNumber'),
                capacity: parseInt(formData.get('capacity')),
                currentOccupancy: 0,
                buildingId: parseInt(formData.get('buildingId'))
            };

            try {
                loading.show();
                await API.rooms.create(room);
                hideModal('addRoomModal');
                this.loadRooms();
                e.target.reset();
            } catch (error) {
                Debug.error('添加房间失败:', error);
                alert('添加房间失败: ' + error.message);
            } finally {
                loading.hide();
            }
        });

        // 监听宿舍楼选择变化
        document.getElementById('buildingSelect').addEventListener('change', () => {
            this.loadRooms();
        });
    },

    // 显示房间列表
    async showRooms(rooms) {
        const roomList = document.getElementById('roomList');
        if (!rooms || rooms.length === 0) {
            roomList.innerHTML = `
                <div class="empty-state">
                    <p>暂无房间</p>
                    <button class="btn btn-primary" onclick="RoomManager.showAddForm()">
                        <i class="icon add-icon"></i>添加房间
                    </button>
                </div>
            `;
            return;
        }

        roomList.innerHTML = rooms.map(room => `
            <div class="room-card">
                <div class="room-header">
                    <h3>${room.roomNumber}</h3>
                    <div class="room-stats">
                        <span class="occupancy-rate">
                            入住率: ${((room.currentOccupancy / room.capacity) * 100).toFixed(1)}%
                        </span>
                        <span class="capacity">
                            ${room.currentOccupancy}/${room.capacity}
                        </span>
                    </div>
                </div>
                <div class="room-content">
                    <div class="student-list">
                        ${room.students.map(student => `
                            <div class="student-item">
                                <span>${student.name}</span>
                                <span class="student-number">${student.studentNumber}</span>
                            </div>
                        `).join('') || '<p class="empty-text">暂无学生</p>'}
                    </div>
                </div>
                <div class="room-footer">
                    <button class="btn btn-secondary" onclick="RoomManager.showDetails(${room.id})">
                        <i class="icon student-icon"></i>查看学生
                    </button>
                    <button class="btn btn-primary" onclick="HygieneManager.showRecords(${room.id})">
                        <i class="icon hygiene-icon"></i>卫生记录
                    </button>
                    <button class="btn btn-danger" onclick="RoomManager.delete(${room.id})">
                        <i class="icon delete-icon"></i>删除
                    </button>
                </div>
            </div>
        `).join('');
    }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    RoomManager.init();
}); 